﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using StoreClientModule;
using StoreClientModuleEx;
using uCoreClasses;
namespace MBBStoreClient
{
    public partial class frmPaintMixing : Form
    {
        SalesEntry se = new SalesEntry();
        DataTable item = new DataTable();
        List<ContentDetailType> cdetail = new List<ContentDetailType>();
        StockManager sm = new StockManager();

        public frmPaintMixing()
        {
            InitializeComponent();

            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);
            btnAdd.LostFocus += new EventHandler(btnAdd_LostFocus);

            se.ProcessCompleted += new ModuleEventHandler(se_ProcessCompleted);
            se.ProcessError += new ModuleEventHandler(se_ProcessError);
            txtDescription.KeyPress += new KeyPressEventHandler(txtDescription_KeyPress);
            //txtUnit.KeyPress += new KeyPressEventHandler(txtUnit_KeyPress);
            txtQty.LostFocus += new EventHandler(txtQty_LostFocus);
            btnAdd.LostFocus += new EventHandler(btnAdd_LostFocus);
            btnAdd.Click += new EventHandler(btnAdd_Click);
            btnSave.Click += new EventHandler(btnSave_Click);
            mnuCancel.Click += new EventHandler(mnuCancel_Click);

            sm.PreloadUnits();
            sm.ProcessCompleted += new UnityCore.CoreHandler(sm_ProcessCompleted);
            sm.ProcessError += new UnityCore.CoreHandler(sm_ProcessError);
        }
        void sm_ProcessError(string pcode, string msg)
        {
            uThreader t = new uThreader();
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg, pcode, MessageBoxButtons.OK, MessageBoxIcon.Error);
            });
        }
        void sm_ProcessCompleted(string pcode, string msg)
        {
            uThreader t = new uThreader();
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "UpdateStock":
                        ControlState(true);

                        foreach (Control ctl in pnlAdd.Controls)
                        {
                            if (!(ctl is Button) && !(ctl is Label))
                            {
                                ctl.Text = "";
                            }
                        }
                        item.Rows.Clear();
                        cdetail.Clear();
                        pnlMsg.Visible = false;
                        MessageBox.Show("Sales record was successfully saved.", "Sales Entry", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        break;
                }
            });
        }
        void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                bool hasError = false;
                if (item.Rows.Count == 0) hasError = true;
                if (hasError)
                {
                    MessageBox.Show("Invalid inputs detected! Please check item list and sale details.",
                        "Commit Entry", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                SalesType st = new SalesType();
                st.Items = new SalesItemType[item.Rows.Count];
                for (int i = 0; i < st.Items.Length; i++)
                {
                    st.Items[i].fInvoice = "Mix";
                    st.Items[i].fBarcode = cdetail[i].fBarcode;
                    st.Items[i].fQty = item.Rows[i]["Qty"].ToString();
                    st.Items[i].fUnit = item.Rows[i]["Unit"].ToString();
                    st.Items[i].fDescription = item.Rows[i]["Description"].ToString();
                    st.Items[i].fUnitPrice = "";
                    st.Items[i].fContentQty = cdetail[i].fQty;
                    st.Items[i].fContentUnit = cdetail[i].fUnit;
                    st.Items[i].fContentBarcode = cdetail[i].fBarcode;
                }
                ControlState(false);

                sm.UpdateStock(st.Items);
                //se.AddMix(st);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Commit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //MessageBox.Show("Error during commit! Please check your input.", "Commit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void mnuCancel_Click(object sender, EventArgs e)
        {
            if (grdItems.SelectedRows.Count == 1)
            {
                DialogResult dlg = MessageBox.Show("Are you sure?", "Entry Cancel", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlg == DialogResult.Yes)
                {
                    cdetail.RemoveAt(grdItems.SelectedRows[0].Index);
                    item.Rows[grdItems.SelectedRows[0].Index].Delete();
                }
            }
        }
        void btnAdd_Click(object sender, EventArgs e)
        {
            AddItem();
        }
        void AddItem()
        {
            bool inpValid = true;
            //Add if new item
            string[] invChar = { "'", "#", "%", "@", "\"" };
            foreach (Control ctl in pnlAdd.Controls)
            {
                if (ctl is TextBox || ctl is ComboBox)
                {
                    for (int i = 0; i < invChar.Length; i++)
                    {
                        if (ctl.Text.Contains(invChar[i])) inpValid = false;
                        if (ctl.Text == "") inpValid = false;
                    }
                }
            }
            if (inpValid)
            {
                ContentDetailType cdt = se.GetContent(txtDescription.Text, txtUnit.Text);
                if (cdt.fBarcode != "N\\A")
                {
                    cdetail.Add(cdt);

                    if (float.Parse(txtQty.Text) > 0 && txtUnit.Text != "")
                    {
                        //check if decimal
                        float dec = (float)(Math.Round(decimal.Parse(txtQty.Text), 0)) - float.Parse(txtQty.Text);
                        if (txtUnit.Text == "PCS" && dec != 0)
                        {
                            MessageBox.Show("Invalid quantity detected! The unit is in PCS, the quantity should not contain decimal values.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return;
                        }
                        DataRow dr = item.NewRow();
                        dr["Barcode"] = cdt.fBarcode;
                        dr["Qty"] = txtQty.Text;
                        dr["Unit"] = txtUnit.Text;
                        dr["Description"] = txtDescription.Text;
                        
                        item.Rows.Add(dr);

                        ResetAdd();
                    }
                    else
                    {
                        MessageBox.Show("Invalid values have been detected!\n" +
                            " You could have a missing field or inappropriate values.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {

                    MessageBox.Show("Invalid values have been detected!\n" +
                           "The system could not identify the product or an inaapropriate unit is assigned to the item.", "Add Item", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

            }
            else
            {
                MessageBox.Show("Invalid inputs! The characters ', #, %, @, \" are not valid.", "Item Add", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
      
        void btnAdd_LostFocus(object sender, EventArgs e)
        {
            txtQty.Focus();
        }

        void txtQty_LostFocus(object sender, EventArgs e)
        {
            txtQty.Text = Common.FormatNumber(txtQty.Text);
        }
        /*void txtUnit_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar != (char)27 && e.KeyChar != (char)13)
                {
                    if (txtUnit.Items.Count > 0) txtUnit.DroppedDown = true; else txtUnit.DroppedDown = false;
                    se.AutoUnit(txtUnit.Text);
                }
                else
                {
                    txtUnit.DroppedDown = false;
                }
            }
            catch (Exception ex)
            {
            }
        }*/
        void txtDescription_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar != (char)27 && e.KeyChar != (char)13)
                {
                    if (txtDescription.Items.Count > 0) txtDescription.DroppedDown = true; else txtDescription.DroppedDown = false;
                    se.AutoDescription(txtDescription.Text);
                }
                else
                {
                    txtDescription.DroppedDown = false;
                }
            }
            catch (Exception ex)
            {
            }
        }
        void se_ProcessError(string procCode, string msg)
        {
            uThreader t = new uThreader();
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg, procCode, MessageBoxButtons.OK, MessageBoxIcon.Error);
                ControlState(true);
            });
        }
        void se_ProcessCompleted(string procCode, string msg)
        {
            uThreader t = new uThreader();
            t.SafeCall(this, delegate
            {
                if (procCode == "AutoDescription")
                {
                    if (se.ListAutoDescription.Length > 0)
                    {
                        txtDescription.Items.Clear();
                        txtDescription.Items.AddRange(se.ListAutoDescription);
                        txtDescription.SelectionStart = txtDescription.Text.Length;
                    }
                }
                if (procCode == "AutoUnit")
                {
                    if (se.ListAutoUnit.Length > 0)
                    {
                        txtUnit.Items.Clear();
                        txtUnit.Items.AddRange(se.ListAutoUnit);
                        txtUnit.SelectionStart = txtUnit.Text.Length;
                    }
                }
               

            });
        }

        void ControlState(bool s)
        {
            pnlAdd.Enabled = s;
            btnSave.Enabled = s;
            pnlMsg.Visible = !s;
        }
        void ResetAdd()
        {
            txtQty.Text = "";
            txtUnit.Text = "";
            txtDescription.Text = "";
            txtQty.Focus();
        }

        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlForm.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlForm; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;

            se.AutoDescription("");
            se.AutoUnit("");

            item.Columns.Add("Qty");
            item.Columns.Add("Unit");
            item.Columns.Add("Description");
            item.Columns.Add("Barcode");
            grdItems.Font = new Font("Courier New", 8f, FontStyle.Regular);
            grdItems.DataSource = item;
            grdItems.Columns[0].Width = (grdItems.Width * 10) / 100;
            grdItems.Columns[1].Width = (grdItems.Width * 10) / 100;
            grdItems.Columns[2].Width = (grdItems.Width * 70) / 100;

            grdItems.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
           
        }
    }
}
